﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure.Dao;
using DormMS.IService;
using DormMS.Model;
using SqlSugar;
using Infrastructure;
using ServiceStack;

namespace DormMS.Service
{
    public class SystemService : ISystemService
    {
        public SystemConfiguration SystemManage()
        {
            using (var Db = DbConfig.GetInstance())
            {
                var model = Db.Queryable<SystemConfiguration>().SingleOrDefault();
                if (model == null || model.Id == 0)
                {
                    int Id = Db.Insert(new SystemConfiguration(), true).ObjToInt();
                    model = Db.Queryable<SystemConfiguration>().SingleOrDefault(m => m.Id == Id);
                }
                return model;
            }
        }


        public Result KeyWordSave(int Id, string keywords, int currentUserId,int? stockwarning)
        {
            using (var Db = DbConfig.GetInstance())
            {
                Db.Update<SystemConfiguration>(new { SearchKeywords = keywords, EditTime = DateTime.Now, EditUserId = currentUserId, StockWarning= stockwarning }, m => m.Id == Id);
                return Result.Success();
            }
        }

        #region WAP

        public List<string> GetSearchKeywords()
        {
            using (var Db = DbConfig.GetInstance())
            {
                var model = Db.Queryable<SystemConfiguration>().SingleOrDefault();
                if (model != null && model.Id > 0 && !model.SearchKeywords.IsNullOrEmpty())
                {
                    return model.SearchKeywords.TrimEnd(',').Split(',').ToList();
                }
                return new List<string>();
            }
        }

        #endregion

        /// <summary>
        /// 获取所有配置内容
        /// </summary>
        /// <returns></returns>
        public List<SystemConfiguration> GetSystemConfiguration()
        {
            using (var Db = DbConfig.GetInstance())
            {
                var model = Db.Queryable<SystemConfiguration>().ToList();
                
                return model;
            }
        }

        /// <summary>
        /// 通过检索关键关键字获取配置内容
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        public SystemConfiguration GetSystemManageInfo(string search)
        {
            using (var Db = DbConfig.GetInstance())
            {
                var model = Db.Queryable<SystemConfiguration>().FirstOrDefault(x => x.SysConfigName == search);
                return model;
            }
        }
        

    }
}
